# @Time : 2021/8/3 14:59
# @Author : Li Kunlun
# @Description : 自动求梯度
from mxnet import autograd, nd

"""
1、对 y=2*x^T*X 求关于列向量x的梯度
"""
x = nd.arange(4).reshape((4, 1))
print(x)
# 1、先调用attach_grad函数来申请存储梯度所需要的内存
x.attach_grad()

# 2、调用record函数来要求MXNet记录与求梯度有关的计算
with autograd.record():
    # y = 2 * nd.dot(x.T, x)
    y = x * x

# [[ 0.]
#  [ 1.]
#  [ 4.]
#  [ 9.]]
# <NDArray 4x1 @cpu(0)>
print(y)
# 3、通过调用backward函数自动求梯度
y.backward()

# 4、验证计算梯度是否正确

# [[ 0.]
#  [ 2.]
#  [ 4.]
#  [ 6.]]
print(x.grad)
